package org.vacoor.ticket.util;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientFactory {
	private HttpClient client;
	private static HttpClientFactory httpUtil;

	private HttpClientFactory() {
		client = new DefaultHttpClient();
		//设置Cookie保存策略
		HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
		// http协议支持
		Scheme http = new Scheme("http", 80,
				PlainSocketFactory.getSocketFactory());
		SSLContext sc = null;
		try {
			sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
					new java.security.SecureRandom());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 不验证域名
		SSLSocketFactory sf = new SSLSocketFactory(sc,
				SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		// SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
		// https协议
		Scheme https = new Scheme("https", 443, sf);
		client.getConnectionManager().getSchemeRegistry().register(http);
		client.getConnectionManager().getSchemeRegistry().register(https);
	}

	synchronized public static HttpClientFactory getInstance() {
		if (httpUtil == null) {
			httpUtil = new HttpClientFactory();
		}
		return httpUtil;
	}
	
	public HttpClient getHttpClient() {
		return client;
	}

	private static class TrustAnyTrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}
}
